<?php

namespace Database\Factories;

use App\Models\ESCluster;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Arr;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Correction>
 */
class CorrectionFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        for ($i=0; $i < 60; $i++) { 
            $interval = $i * 5;
            $time = date("Y-m-d H:i:00",strtotime("-$interval minute"));
            $bms = Arr::random([90, 91, 92, 92, 95, 96, 96, 97, 97, 97, 99, 100]);
            $diff =  Arr::random([0,-1, 0, 2, 2, 3, -2, 1, 1, 3, 2, -1, 2]);
            $algorithm = $bms + $diff ;
            $item = [
                'time' => $time,
                'bms' => $bms,
                'algorithm' => $algorithm,
                'diff' => $diff,
            ];
            $error_curve[$i] = $item;
        }
        $batteries = [ 
            ['rank' => 1, 'name' => "0#电池模组", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 2, 'name' => "1#电池模组", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 3, 'name' => "2#电池模组", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 4, 'name' => "3#电池模组", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 5, 'name' => "4#电池模组", 'deviation' => "5%", 'loss_power' => "12kwh"]
        ];
        $battery_cells = [ 
            ['rank' => 1, 'name' => "0#-0号", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 2, 'name' => "0#-1号", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 3, 'name' => "0#-2号", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 4, 'name' => "0#-3号", 'deviation' => "5%", 'loss_power' => "12kwh"],
            ['rank' => 5, 'name' => "0#-4号", 'deviation' => "5%", 'loss_power' => "12kwh"]
        ];
        $deviation = ['充电截至SOC' => '95%', '放电截至SOC' => '15.0%', '最大SOC误差' => '5%', '损失电量估算' => '14kWh'];
        $deviation_rank = [ '电池模组SOC误差排行' => $batteries, '电芯SOC误差排行' => $battery_cells];
        $advice = ['建议充电截至SOC' => '96.0%', '建议放电截至SOC' => '5.0%', '检查更换BMU建议' => 0 ];
        $type = Arr::random(['SOC校正', 'SOH校正']);
        $data = [
            'dev_id' => $this->faker->randomElement(ESCluster::all()->pluck('id')),
            'dev_type' => 'App\Models\ESCluster', 
            'type' => $type,
            'deviation' => $deviation,
            'deviation_rank' => $deviation_rank,
            'advice' => $advice,
            'error_curve' => $error_curve,
            'remarks' => '备注'
        ];
        if ($type == 'SOH校正'){
            $str = json_encode($data);
            $new = str_replace("SOC", "SOH", $str);
            $data = json_decode($new, TRUE);
        }
        return $data;
    }
}
